package com.qfedu.dao.impl;

import com.qfedu.dao.CreditCardDao;
import com.qfedu.pojo.Cards;
import com.qfedu.pojo.CreditCard;
import com.qfedu.utils.DruidUtil;
import org.apache.commons.dbutils.QueryRunner;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;

import java.sql.Connection;
import java.sql.SQLException;
import java.util.List;

public class CreditCardDaoImpl implements CreditCardDao {
    JdbcTemplate jdbcTemplate = new JdbcTemplate(DruidUtil.getDataSource());
    QueryRunner queryRunner = new QueryRunner();
    @Override
    public CreditCard findCreditCard(String phone) {
        String sql = "select *from credit_card where phone=?";
        List<CreditCard> query = jdbcTemplate.query(sql, new BeanPropertyRowMapper<>(CreditCard.class), phone);
        if(query!=null&&query.size()>0){
            return query.get(0);
        }
        return null;
    }

    @Override
    public int addCreditCard(CreditCard creditCard) {
        String sql = "insert into credit_card(idcode,name,cardnumber,phone,maxOverdraft) values(?,?,?,?,?)";
        int update = jdbcTemplate.update(sql, creditCard.getIdcode(), creditCard.getName(),creditCard.getCardnumber(), creditCard.getPhone(), creditCard.getMaxOverdraft());
        return update;
    }

    @Override
    public CreditCard findCardsnumber(String cardnumber) {
        String sql = "select *from credit_card where cardnumber=?";
        List<CreditCard> query = jdbcTemplate.query(sql, new BeanPropertyRowMapper<>(CreditCard.class), cardnumber);
        if(query!=null&&query.size()==1){
            return query.get(0);
        }
        return null;
    }

    @Override
    public void inMoney(CreditCard target, int money, Connection connection) {
        String sql = "update credit_card set balance = balance+? where cardnumber =?";
        try {
            queryRunner.update(connection, sql, money, target.getCardnumber());
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
    }


    @Override
    public void outMoney2(CreditCard source, double money, Connection connection) {
        String sql = "update credit_card set balance = balance-? where cardnumber =?";
        try {
            queryRunner.update(connection, sql, money, source.getCardnumber());
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
    }

    @Override
    public List<CreditCard> findIdcodeCredit(String idcode) {
        String sql = "select *from credit_card where idcode=?";
        List<CreditCard> query = jdbcTemplate.query(sql, new BeanPropertyRowMapper<>(CreditCard.class), idcode);
        if(query!=null&&query.size()>0){
            return query;
        }
        return null;
    }
}
